<template>
  <div class="Design">
    <div style="text-align: center; vertical-align: middle">
      <!-- 表单标题 -->

      <h2
        @click="titleClick"
        v-if="!titleChange"
        style="background-color: rgb(239, 239, 239)"
      >
        {{ title }}
      </h2>

      <el-input
        v-if="titleChange"
        v-model="title"
        @blur="onblur"
        @keyup.enter="onsubmit"
        ref="titleInput"
        style="width: 200px; height: 60px"
      ></el-input>
      <!-- 表单描述 -->

      <h4
        @click="descClick"
        v-if="!descChange"
        style="background-color: rgb(239, 239, 239)"
      >
        {{ description }}
      </h4>

      <el-input
        v-if="descChange"
        v-model="description"
        @blur="onblurDesc"
        @keyup.enter="onsubmitDesc"
        ref="descInput"
        style="width: 200px; height: 60px"
      ></el-input>
    </div>
    <el-card
      class="box-card"
      v-for="(item, index) in detail"
      style="margin: 10px"
    >
      <div slot="header" class="clearfix">
        <div class="questionTitle">
          <!--显示必填标识-->
          <span style="color: #f56c6c">
            <span v-if="item.must">*</span>
            <span v-else>&nbsp;</span>
          </span>
          <span style="color: black; margin-right: 3px">{{
            index + 1 + "."
          }}</span>
          {{ item.title }}
        </div>

        <div style="float: right">
          <el-button
            style="padding: 2px"
            type="text"
            @click="editorQuestion(item, index)"
            >编辑</el-button
          >
          <el-button
            style="padding: 2px; color: #f56c6c"
            type="text"
            @click="deleteQuestion(index)"
            >删除</el-button
          >
        </div>
      </div>

      <!--单选题展示-->
      <div
        class="text item"
        v-if="item.type == 'radio'"
        v-for="(option, index) in item.options"
      >
        <el-radio
          v-model="item.radioValue"
          :label="index"
          style="margin: 5px"
          >{{ option.title }}</el-radio
        >
      </div>

      <!--多选题展示-->
      <div
        class="text item"
        v-if="item.type == 'checkbox'"
        v-for="(option, index) in item.options"
      >
        <el-checkbox :label="index" style="margin: 5px">{{
          option.title
        }}</el-checkbox>
      </div>
      <!--填空题展示-->
      <el-input
        v-if="item.type == 'text'"
        type="textarea"
        :rows="item.rowNum"
        resize="none"
        v-model="item.textValue"
      >
      </el-input>
    </el-card>
    <br /><br />
    <div id="footer">
      <div class="block">
        <div style="margin-left: 50px">
          <span class="demonstration">设置截止时间 </span>

          <el-date-picker
            v-model="finishDate"
            type="datetime"
            placeholder="选择日期时间"
            default-time="12:00:00"
          >
          </el-date-picker>
        </div>
      </div>
      <br /><br />
      <div
        style="text-align: center; vertical-align: middle; text-align: center"
      >
        <el-button
          icon="el-icon-circle-plus"
          @click="addQuestion"
          style="margin-top: 10px"
          >添加题目</el-button
        >
        <el-button
          icon="el-icon-remove"
          @click="exitCreate"
          style="margin-top: 10px"
          >取消</el-button
        >
        <el-button
          icon="el-icon-success"
          @click="saveWj"
          style="margin-top: 10px"
          >保存</el-button
        >
      </div>
    </div>
    <br /><br /><br /><br /><br />

    <!--添加题目弹窗-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogShow"
      :close-on-click-modal="false"
      class="dialog"
    >
      <el-form ref="form" :model="willAddQuestion" label-width="80px">
        <el-form-item label="题目类型" style="width: 100%">
          <el-select
            v-model="willAddQuestion.type"
            placeholder="请选择题目类型"
            @change="typeChange"
          >
            <el-option
              v-for="item in allType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否必填" style="width: 100%">
          <el-checkbox v-model="willAddQuestion.must">必填</el-checkbox>
        </el-form-item>
        <el-form-item label="题目标题" style="width: 100%">
          <el-input
            v-model="willAddQuestion.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>

        <template
          v-if="
            willAddQuestion.type == 'radio' ||
            willAddQuestion.type == 'checkbox'
          "
        >
          <el-form-item
            :label="'选项' + (index + 1)"
            v-for="(item, index) in willAddQuestion.options"
          >
            <el-row>
              <el-col :span="16">
                <el-input
                  v-model="item.title"
                  placeholder="请输入选项名"
                  style="width: 90%"
                ></el-input>
              </el-col>
              <el-col :span="8">
                <el-button
                  type="danger"
                  plain
                  class=""
                  @click="deleteOption(index)"
                  >删除选项</el-button
                >
              </el-col>
            </el-row>
          </el-form-item>
          <el-button
            type="primary"
            plain
            class="addOptionButton"
            @click="addOption"
            >新增选项</el-button
          >
        </template>
        <template v-if="willAddQuestion.type == 'text'">
          <el-form-item label="填空">
            <el-input
              type="textarea"
              :rows="willAddQuestion.rowNum"
              style="width: 80%"
              resize="none"
            ></el-input>
          </el-form-item>
          <el-form-item label="行数">
            <el-input-number
              v-model="willAddQuestion.rowNum"
              :min="1"
              :max="10"
              label="描述文字"
            ></el-input-number>
          </el-form-item>
        </template>
      </el-form>
      <br />
      <div style="width: 100%; text-align: right">
        <el-button style="margin-left: 10px" @click="dialogShow = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="checkAddQuestion"
          >完成</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      edit: false,
      id: 0,
      dialogShow: false,
      isAdd: false,
      dialogTitle: "",
      detail: [],
      lastForm: {},
      wjId: 0,
      titleChange: false,
      descChange: false,
      title: "标题",
      titleValue: "标题",
      description: "表单描述",
      descValue: "表单描述",
      questions: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      finishDate: "2021-02-01 12:00:00",
      createDate: "",

      willAddQuestion: {
        // id: 0,
        type: "",
        title: "",
        options: [
          // {
          //   title: "", //选项标题
          //   // id: 0, //选项id
          // },
        ],
        rowNum: 1,
        must: false, //是否必填
      },
      allType: [
        {
          value: "radio",
          label: "单选题",
        },
        {
          value: "checkbox",
          label: "多选题",
        },
        {
          value: "text",
          label: "填空题",
        },
      ],
    };
  },

  mounted() {
    //判断此界面是否通过主页面点击编辑传过来的
    this.edit = this.$route.params.flag;

    console.log(this.edit);
    //如果是
    if (this.edit == true) {
      //接收qs_create界面传过来的参数
      this.lastForm = this.$route.params.form;
      this.title = this.lastForm.title;
      this.description = this.lastForm.description;
      this.finishDate = this.lastForm.finishDate;
      //暂存问题

      this.detail = this.lastForm.questions;
      // this.questions = this.lastForm.questions;

      console.log(JSON.stringify(this.lastForm));
    }
  },

  methods: {
    onblur() {
      this.title = this.title.trim();
      if (this.title === "") {
        this.title = this.titleValue;
      }
      this.titleChange = false;
    },
    onsubmit() {
      this.title = this.title.trim();
      if (this.title === "") {
        this.title = this.titleValue;
      }
      this.titleChange = false;
    },
    titleClick() {
      this.titleChange = !this.titleChange;
      setTimeout(() => {
        this.$refs.titleInput.focus();
      }, 150);
    },
    onblurDesc() {
      this.description = this.description.trim();
      if (this.description === "") {
        this.description = this.descValue;
      }
      this.descChange = false;
    },
    onsubmitDesc() {
      this.description = this.description.trim();
      if (this.description === "") {
        this.description = this.descValue;
      }
      this.descChange = false;
    },
    descClick() {
      this.descChange = !this.descChange;
      setTimeout(() => {
        this.$refs.descInput.focus();
      }, 150);
    },
    //点击添加问题按钮
    addQuestion() {
      this.dialogTitle = "添加题目";
      this.willAddQuestion = {
        // id: 0,
        type: "",
        title: "",
        options: [
          // {
          //   title: "", //选项标题
          //   // id: 0, //选项id
          // },
        ],
        rowNum: 1,
        must: false, //是否必填
        // checkboxValue: []
      };
      this.dialogShow = true;
      this.isAdd = true;
      // this.detail.push(this.willAddQuestion);
    },
    //确认添加/保存题目
    checkAddQuestion() {
      this.dialogShow = false;
      if (this.isAdd == true) {
        this.detail.push(this.willAddQuestion);
        this.isAdd = false;
      }
    },
    //删除问题
    deleteQuestion(index) {
      this.$confirm("确定删除此题目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.detail.splice(index, 1);
      });
    },
    exitCreate() {
      this.$confirm("确定取消创建?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$router.push({
          path: "/",
        });
      });
    },

    //点击编辑问题按钮
    editorQuestion(item, index) {
      this.willAddQuestion.title = item.title;
      this.willAddQuestion.type = item.type;
      this.willAddQuestion.options = JSON.parse(JSON.stringify(item.options));
      // this.willAddQuestion.text = item.text;
      this.willAddQuestion.rowNum = item.rowNum;
      this.willAddQuestion.must = item.must;
      this.willAddQuestion.id = item.id;
      this.dialogTitle = "编辑问题";
      this.dialogShow = true;
    },
    //添加选项
    addOption() {
      this.willAddQuestion.options.push({
        title: "",
        // id: 0,
      });
    },
    //删除选项
    deleteOption(index) {
      this.willAddQuestion.options.splice(index, 1);
    },
    //切换问题类型
    typeChange(value) {
      console.log(value);
      this.willAddQuestion.type = value;
      // this.willAddQuestion.text = "";
      this.rowNum = 1;
    },
    saveWj() {
      this.$confirm("确定保存?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.getLastForm();
        let datas = JSON.stringify(this.lastForm);
        console.log(datas);

        axios({
          method: "post",
          url: "http://localhost:8082/userForm/save",
          headers: {
            "Content-Type": "application/json",
          },
          data: datas,
        });

        this.$router.push({
          path: "/",
        });
        //刷新界面
        window.location.reload();
      });
    },
    getLastForm() {
      this.lastForm.title = this.title;
      this.lastForm.description = this.description;

      this.lastForm.createdDate = this.dateFormat(
        "YYYY-mm-dd HH:MM:SS",
        new Date()
      );

      this.lastForm.finishDate = this.dateFormat(
        "YYYY-mm-dd HH:MM:SS",
        new Date(this.finishDate)
      );

      this.lastForm.status = false;
      this.lastForm.questions = this.detail;
    },
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },
  },
};
</script>

<style scoped>
.Design {
  padding-top: 20px;
}

#footer {
  width: 100%;
  bottom: 5px;
  background-color: rgb(239, 239, 239);
  color: black;
  clear: both;
  padding: 0px;
  clear: both;
  position: fixed;
}
</style>
